package com.yokead.controller.domain;

import cn.jiangzeyin.StringUtil;
import cn.jiangzeyin.common.JsonMessage;
import cn.jiangzeyin.common.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yokead.common.Config;
import com.yokead.common.base.AdminBaseControl;
import com.yokead.controller.sysadmin.domain.KhDoMainConfControl;
import com.yokead.service.domain.DoMainServer;
import com.yokead.system.log.LogType;
import com.yokead.system.log.SystemLog;
import com.yokead.util.JsonUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author jiangzeyin
 * @date 2017/10/11
 */
@Controller
@RequestMapping("domain")
public class KhDoMainControl extends AdminBaseControl {

    @Resource
    private DoMainServer doMainServer;

    @RequestMapping(value = "adkh.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String adkh() {
        return "domain/adkh";
    }

    /**
     * @param url
     * @return
     */
    @RequestMapping(value = "del_kh_domain.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String delKhDomain(String url, String delType) {
        if (StringUtil.isEmpty(url)) {
            return JsonMessage.getString(400, "请输入链接");
        }
        synchronized (KhDoMainControl.class) {
            JSONObject jsonObject;
            try {
                jsonObject = doMainServer.getUrls();
            } catch (IOException e) {
                SystemLog.LOG(LogType.CONTROL_ERROR).error("读取异常", e);
                return JsonMessage.getString(500, "删除时，系统异常，请稍后重试");
            }
            if (jsonObject == null) {
                return JsonMessage.getString(500, "删除时，系统异常，请稍后重试：-3");
            }

            JSONObject customer = null;
            if ("customer".equals(delType)) {
                customer = jsonObject.getJSONObject(delType);
            } else if (isManager()) {
                customer = jsonObject.getJSONObject("default");
            }
//            "customer"
            if (customer == null) {
                return JsonMessage.getString(400, "删除时，系统异常，请稍后重试：-4");
            }
            //
            DoMainControl doMainControl = SpringUtil.getBean(DoMainControl.class);
            JsonMessage jsonMessage = doMainControl.getChild(url);
            // 不成功  或者 不存在
            if (jsonMessage.getCode() != 200 && jsonMessage.getCode() != 400) {
                return jsonMessage.toString();
            }
            JSONArray jsonArray;
            if ("customer".equals(delType)) {
                jsonArray = customer.getJSONArray(userName);
            } else {
                jsonArray = customer.getJSONArray(delType);
            }
            if (jsonArray == null || !jsonArray.contains(url)) {
                return JsonMessage.getString(404, "没有找到" + url + "域名");
            }
            jsonArray.remove(url);
            JSONArray urlData = (JSONArray) jsonMessage.getData();
            if (urlData != null) {
                KhDoMainConfControl khDoMainConfControl = SpringUtil.getBean(KhDoMainConfControl.class);
                for (Object object : urlData) {
                    JSONObject jsonObject1 = (JSONObject) object;
                    String type = jsonObject1.getString("type");
                    if ("A".equalsIgnoreCase(type)) {
                        String name = jsonObject1.getString("name");
                        name += "." + url;
                        // 删除配置信息
                        JsonMessage jsonMessage1 = khDoMainConfControl.removeConfig(name);
                        if (jsonMessage1 != null) {
                            return jsonMessage1.toString();
                        }
                    }
                }
            }

            String path = Config.DnsPodConfig.getDnsPodDomainListFile();
            try {
                JsonUtil.saveJson(path, jsonObject);
            } catch (IOException e) {
                SystemLog.LOG(LogType.CONTROL_ERROR).error("删除异常", e);
                return JsonMessage.getString(500, "删除异常");
            }
            return JsonMessage.getString(200, "ok del");
        }
    }

    @RequestMapping(value = "save_kh_domain.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String save_kh_domain(String url) {
        if (StringUtil.isEmpty(url)) {
            return JsonMessage.getString(400, "请输入链接");
        }
        synchronized (KhDoMainControl.class) {
            JSONObject jsonObject;
            try {
                jsonObject = doMainServer.getUrls();
            } catch (IOException e) {
                SystemLog.LOG(LogType.CONTROL_ERROR).error("读取异常", e);
                return JsonMessage.getString(500, "系统异常，请稍后重试");
            }
            if (jsonObject == null) {
                return JsonMessage.getString(500, "系统异常，请稍后重试：-1");
            }
            JSONObject customer = jsonObject.getJSONObject("customer");
            if (customer == null) {
                customer = new JSONObject();
                jsonObject.put("customer", customer);
            }
            // return JsonMessage.getString(400, "系统异常，请稍后重试：-2");
            JSONArray jsonArray = customer.getJSONArray(userName);
            if (jsonArray == null) {
                jsonArray = new JSONArray();
                customer.put(userName, jsonArray);
            }
            if (jsonArray.contains(url)) {
                return JsonMessage.getString(401, "域名已经存在");
            }
            jsonArray.add(url);
            String path = Config.DnsPodConfig.getDnsPodDomainListFile();
            // getBootPath() + "/domain_list.conf";
            try {
                JsonUtil.saveJson(path, jsonObject);
            } catch (IOException e) {
                SystemLog.LOG(LogType.CONTROL_ERROR).error("保存异常", e);
                return JsonMessage.getString(500, "保存异常");
            }
            return JsonMessage.getString(200, "ok");
        }
    }
}
